package http;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import net.htmlparser.jericho.Source;

public class Page extends SubjectImpl {
	private boolean downloaded = false;
	private String uri;
	private URL url;
	private URLConnection connection;
	private URLConnection postConnection;
	private List<IParserStrategy> parser = new ArrayList<IParserStrategy>();
	private Source source;
	public final int DOWNLOADED = 200;
	public final int ERROR = 400;
	public String getUri() {
		return uri;
	}
	public URLConnection getConnection() {
		return connection;
	}
	public URL getUrl() {
		return url;
	}
	public boolean isDownloaded() {
		return downloaded;
	}
	public Page(String uri) throws MalformedURLException {
		System.out.println("Opening GET-Connection...");
		this.uri = uri;
		this.url = new URL(this.uri);
	}
	public Page(CaptchaForm form) throws MalformedURLException {
		this.uri = form.toString();
		this.url = new URL(this.uri);
		if (form.getMethod() == CaptchaForm.GET) {
			System.out.println("Opening GET-Connection to "+this.uri+" ...");
		}
		else {
			System.out.println("Opening POST-Connection to "+this.uri+" (POST-Data: "+form.getPostMessage()+") ...");
			try {
				postConnection = this.url.openConnection();
				postConnection.setDoOutput(true);
				postConnection.getOutputStream().write(form.getPostMessage().getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	public void open() throws IOException {
		this.url = new URL(this.uri);
		if (source == null) {
			System.out.println("Opening Page: "+this.url.toString());
			if (postConnection == null) {
				this.connection = this.url.openConnection();
				this.connection.setConnectTimeout(1000*60*10);
				source = new Source(this.connection);
			}
			else {
				this.connection = postConnection;
				source = new Source(new InputStreamReader(postConnection.getInputStream()));
				System.out.println(source);
			}
		}
		for (IParserStrategy p:parser)
			p.parse(this.url,source);
	}
	public void addParser(IParserStrategy parser) {
		this.parser.add(parser);
	}
	public void removeParser(IParserStrategy parser) {
		this.parser.remove(parser);
	}
	public void run(Page p) {
		try {
			p.open();
			this.setSubjectState(DOWNLOADED);
		} catch (IOException e) {
			this.setSubjectState(ERROR);
		}
	}
}
